package com.neo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.result.method.RequestMappingInfo;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    RequestMappingHandlerMapping requestMappingHandlerMapping;

    RequestMappingInfo mappingInfo = null;

    @RequestMapping("/hello")
    public Mono<String> index() {
//        Method targetMethod = ReflectionUtils.findMethod(HelloController.class, "registerMappingByGET", Map.class, ServerWebExchange.class);
        Method targetMethod = ReflectionUtils.findMethod(HelloController.class, "registerMappingByPOST", String.class, ServerWebExchange.class);
        if (mappingInfo == null) {
//            mappingInfo = RequestMappingInfo.paths("/he").methods(RequestMethod.GET).build();
            mappingInfo = RequestMappingInfo.paths("/he").methods(RequestMethod.POST).build();
            requestMappingHandlerMapping.registerMapping(mappingInfo, HelloController.this, targetMethod); // 注册映射处理
        } else {
            requestMappingHandlerMapping.unregisterMapping(mappingInfo);
            mappingInfo = null;
        }
        return Mono.just("hello world!");
    }

    @ResponseBody
    public String registerMappingByPOST(@RequestBody String data, ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        for (Map.Entry<String, List<String>> stringListEntry : headers.entrySet()) {
            System.out.println(stringListEntry);
        }
        System.out.println(data);
        return "a" + data;
    }

    @ResponseBody
    public String registerMappingByGET(@RequestParam Map map, ServerWebExchange exchange) {
        return "registerMappingByPOST(JSON.toJSONString(map), request)";
    }

    @RequestMapping("/foo")
    public String foo(String foo, ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        for (Map.Entry<String, List<String>> stringListEntry : headers.entrySet()) {
            System.out.println(stringListEntry);
        }
        String h = headers.getFirst("Connection");
        List<Charset> charsets = headers.getAcceptCharset();
        return "hello " + foo + "!" + charsets.get(0).name();
    }

}